package com.hafiery.sdk.bluetooth.transport.task;

import com.hafiery.sdk.bluetooth.transport.constant.ErrorCode;
import com.hafiery.sdk.bluetooth.transport.engine.Engine;
import com.hafiery.sdk.bluetooth.util.LogUtil;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskManager {
    private ExecutorService executor = Executors.newFixedThreadPool(1);
    private long beginTime=0;
    private Task currentTask;
    private boolean start=true;
    public TaskManager(Engine engine){
        new Thread(() -> {
            while(start){
                if(isDone){
                    currentTask=null;
                    beginTime=0;
                    if(!tasks.isEmpty()){
                        isDone=false;
                        Task task=tasks.removeFirst();
                        currentTask=task;
                        executor.submit(() -> engine.send(task.requestData, task.callBackHandler));
                    }
                }else{
                    if(beginTime==0){
                        beginTime=System.currentTimeMillis();
                    }else{
                        if(System.currentTimeMillis() - beginTime >10*1000){
                            LogUtil.log("超时了:"+currentTask.requestData.getOpCode());
                            currentTask.callBackHandler.callback.onFailure(ErrorCode.ERRCODE_DEVICE_BUSY);
//                            tasks.addLast(currentTask);
                            isDone=true;
                        }
                    }
                }
            }
        }).start();
    }
    private LinkedList<Task> tasks=new LinkedList<>();
    private boolean isDone =true;
    public void addTask(Task task){
        tasks.addLast(task);
    }
    public void next(){
        isDone =true;
    }
    public void stop(){
        start=false;
    }

}
